package city.spring.modules.medicalstation.medicationRecord.controller;

import city.spring.modules.medicalstation.medicationRecord.entity.MedicationRecordEntity;
import city.spring.modules.medicalstation.medicationRecord.service.MedicationRecordService;
import city.spring.modules.medicalstation.medicationRecord.vo.MedicationRecordVO;
import city.spring.utils.MyBatisUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.data.web.SortDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Controller：用药记录
 *
 * @author 谢金婷
 * @date 2020-10-23 16:04:43
 */
@RestController
@RequestMapping("/medication_record")
public class MedicationRecordController extends ApiController {
    private final MedicationRecordService medicationRecordService;
    /**
     * 实体类可排序字段
     */
    private final List<SFunction<MedicationRecordEntity, ?>> entityOrderFields;

    public MedicationRecordController(MedicationRecordService medicationRecordService) {
        this.medicationRecordService = medicationRecordService;
        entityOrderFields = new ArrayList<>();
        entityOrderFields.add(MedicationRecordEntity::getId);
        entityOrderFields.add(MedicationRecordEntity::getDate);
        entityOrderFields.add(MedicationRecordEntity::getTime);
        entityOrderFields.add(MedicationRecordEntity::getMedicationType);
        entityOrderFields.add(MedicationRecordEntity::getRegister);
        entityOrderFields.add(MedicationRecordEntity::getGmtCreate);
        entityOrderFields.add(MedicationRecordEntity::getGmtModified);
    }

    /**
     * 获取全部的 <strong>用药记录</strong> 列表
     */
    @GetMapping("all")
    public Object listAll(@PageableDefault Pageable pageable, MedicationRecordEntity entity) {
        LambdaQueryChainWrapper<MedicationRecordEntity> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        return success(lambdaQuery.list());
    }

    /**
     * 分页获取 <strong>用药记录</strong> 列表
     *
     * @param pageable 分页参数信息
     */
    @GetMapping
    public Object list(@PageableDefault @SortDefault.SortDefaults(@SortDefault(sort = "id", direction = Sort.Direction.DESC)) Pageable pageable, MedicationRecordVO entity, Date[] date) {
//        LambdaQueryChainWrapper<MedicationRecordEntity> lambdaQuery = buildLambdaQuery(entity);
//        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
//        Page<MedicationRecordEntity> page = lambdaQuery.page(MyBatisUtils.toPage(pageable, false));
//        return success(page);
        QueryWrapper<? extends MedicationRecordEntity> queryWrapper = buildQuery(entity);
        if (date != null && date.length == 2) {
            queryWrapper.ge("t1.date", date[0]);
            queryWrapper.le("t1.date", date[1]);
        }
        return success(medicationRecordService.listPage(MyBatisUtils.toPage(pageable), queryWrapper));
    }

    /**
     * 获取一个 <strong>用药记录</strong>
     *
     * @param id 主键ID
     */
    @GetMapping("{id}")
    public Object info(@PathVariable String id) {
        QueryWrapper<MedicationRecordVO> wrapper = new QueryWrapper<>();
        wrapper.eq("t1.id", id);
        List<MedicationRecordVO> records = medicationRecordService.listPage(new Page<>(), wrapper).getRecords();
        if (records.isEmpty()) {
            return success(null);
        }
        return success(records.get(0));
//        return success(medicationRecordService.getById(id));
    }

    /**
     * 添加一个 <strong>用药记录</strong>
     *
     * @param entity 修改后的信息
     */
    @PostMapping
    public Object add(@RequestBody MedicationRecordEntity entity) {
        medicationRecordService.saveMedicationRecord(entity);

//        HttpHeaders headers = new HttpHeaders();
//        headers.add(HttpHeaders.LOCATION, String.valueOf(entity.getId()));
//        return new ResponseEntity<>(headers, HttpStatus.CREATED);
        return success(entity);
    }

    /**
     * 修改一个 <strong>用药记录</strong>
     *
     * @param id     主键ID
     * @param entity 修改后的信息
     */
    @PutMapping("{id}")
    public Object update(@PathVariable String id, @RequestBody MedicationRecordEntity entity) {
        entity.setId(id);
        medicationRecordService.updateMedicationRecord(entity);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 删除一个 <strong>用药记录</strong>
     *
     * @param id 主键ID
     */
    @DeleteMapping("{id}")
    public Object delete(@PathVariable String id) {
        medicationRecordService.deleteMedicationRecord(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 删除多个 <strong>用药记录</strong>
     *
     * @param ids 主键ID列表
     */
    @DeleteMapping
    public Object deleteIds(@RequestBody List<String> ids) {
        medicationRecordService.deleteMedicationRecord(ids);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private LambdaQueryChainWrapper<MedicationRecordEntity> buildLambdaQuery(MedicationRecordEntity entity) {
        LambdaQueryChainWrapper<MedicationRecordEntity> lambdaQuery = medicationRecordService.lambdaQuery();
        lambdaQuery.eq(StringUtils.isNotBlank(entity.getId()), MedicationRecordEntity::getId, entity.getId());
        lambdaQuery.eq(entity.getDate() != null, MedicationRecordEntity::getDate, entity.getDate());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getTime()), MedicationRecordEntity::getTime, entity.getTime());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getMedicationType()), MedicationRecordEntity::getMedicationType, entity.getMedicationType());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getRegister()), MedicationRecordEntity::getRegister, entity.getRegister());
        lambdaQuery.eq(entity.getGmtCreate() != null, MedicationRecordEntity::getGmtCreate, entity.getGmtCreate());
        lambdaQuery.eq(entity.getGmtModified() != null, MedicationRecordEntity::getGmtModified, entity.getGmtModified());
        return lambdaQuery;
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private QueryWrapper<MedicationRecordEntity> buildQuery(MedicationRecordVO entity) {
        QueryWrapper<MedicationRecordEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(entity.getId()), "t1.id", entity.getId());
        wrapper.eq(StringUtils.isNotBlank(entity.getOldmanId()), "t1.oldman_id", entity.getOldmanId());
        wrapper.eq(StringUtils.isNotBlank(entity.getOldmanName()), "t2.oldman_name", entity.getOldmanName());
        wrapper.eq(StringUtils.isNotBlank(entity.getRegister()), "t1.register", entity.getRegister());
        wrapper.eq(StringUtils.isNotBlank(entity.getRegisterName()), "t3.name", entity.getRegisterName());
        wrapper.eq(StringUtils.isNotBlank(entity.getBedName()), "t4.name", entity.getBedName());
        wrapper.eq(entity.getDate() != null, "t1.date", entity.getDate());
        wrapper.like(StringUtils.isNotBlank(entity.getTime()), "t1.time", entity.getTime());
        wrapper.like(StringUtils.isNotBlank(entity.getMedicationType()), "t1.medication_type", entity.getMedicationType());
        wrapper.like(StringUtils.isNotBlank(entity.getRegister()), "t1.register", entity.getRegister());
        return wrapper;
    }

}
